﻿using Kaskelot.SP.Core;
using Kaskelot.SP.Model.Client;
using Microsoft.SharePoint;
using Stockholm.SOA.Kaskelot.WCF.DataContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Kaskelot.SP.Services
{
    public class ApplicationContext
    {
        private static readonly string ContextKey = "KaskelotApplicationContext";
        private static readonly string ValCookie = "KaskelotValId";

        public Val Val { get; set; }
        public Byggnad Byggnad { get; set; }

        #region Singleton
        private ApplicationContext()
        {
			// Val
			HttpCookie valCookie = HttpContext.Current.Request.Cookies.Get(ValCookie);
			Guid? valId = null;
			if (valCookie != null)
			{
				valId = new Guid(valCookie.Value);
			}
			else
			{
				valCookie = new HttpCookie(ValCookie);
			}

			ValService svc = new ValService();
			this.Val = svc.GetVal(valId);

			valCookie.Value = this.Val.Id.ToString();
			valCookie.Expires = DateTime.Now.AddMonths(1);
			HttpContext.Current.Response.AppendCookie(valCookie);

			if (HttpContext.Current.Request.QueryString[Constants.UrlParameters.ByggnadId] != null)
			{
				using (ByggnadService bSvc = new ByggnadService())
				{
					this.Byggnad = bSvc.GetByggnad(this.Val.Id, new Guid(HttpContext.Current.Request.QueryString[Constants.UrlParameters.ByggnadId]));
				}
			}
        }

        public static ApplicationContext Current
        {
            get
            {
                try
                {
                    string key;
                    key = GetKey();

                    if (HttpContext.Current.Cache[key] == null)
                    {
                        HttpContext.Current.Cache.Insert(key, new ApplicationContext(), null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 5));
                    }
                    return HttpContext.Current.Cache[key] as ApplicationContext;
                }
                catch (Exception ex)
                {
                    Logger.LogError(null, LayerNames.Services, "ApplicationContext.Current", "Error initializing the ApplicationContext.", ex);
                    return null;
                }
            }
        }

        private static string GetKey()
        {
			string key = ContextKey + HttpContext.Current.Request.Url + SPContext.Current.Web.CurrentUser.LoginName;
            return key;
        }
        #endregion

		public void SetCurrentVal(Guid id)
		{
			HttpCookie valCookie = valCookie = new HttpCookie(ValCookie);
			valCookie.Value = id.ToString();
			valCookie.Expires = DateTime.Now.AddMonths(1);
			HttpContext.Current.Response.SetCookie(valCookie);

			var enumerator = HttpContext.Current.Cache.GetEnumerator();
			while (enumerator.MoveNext())
			{
				HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
			}
		}
	}
}
